package com.bazaaroid.server.gae.security;

import java.util.Date;

import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.bazaaroid.server.gae.core.dao.UserDAO;
import com.bazaaroid.server.gae.core.ioc.GuiceFactory;
import com.bazaaroid.server.gae.core.persistence.model.User;

public class BazaaroidUserDetailsService implements UserDetailsService {

	public BazaaroidUserDetailsService() {
		Date date = new Date();
		UserDAO userDAO = GuiceFactory.getInjector().getInstance(UserDAO.class);

		User admin = userDAO.getUserByUsername("admin");
		if (admin == null) {
			admin = new User();
			admin.setCreated(date);
			admin.setUsername("admin");
			admin.setPassword(PasswordService.encryptSha("pass"));
			admin.setType(0);
			admin.setAccountNonExpired(true);
			admin.setAccountNonLocked(true);
			admin.setCredentialsNonExpired(true);
			admin.setEnabled(true);
			userDAO.makePersistent(admin);
		}

		User partner = userDAO.getUserByUsername("partner");
		if (partner == null) {
			partner = new User();
			partner.setCreated(date);
			partner.setUsername("partner");
			partner.setPassword(PasswordService.encryptSha("pass"));
			partner.setType(2);
			partner.setAccountNonExpired(true);
			partner.setAccountNonLocked(true);
			partner.setCredentialsNonExpired(true);
			partner.setEnabled(true);
			userDAO.makePersistent(partner);
		}
	}
	@Override
	public UserDetails loadUserByUsername(String username) {
		UserDAO userDAO = GuiceFactory.getInjector().getInstance(UserDAO.class);

		User user = userDAO.getUserByUsername(username);

		if (user == null) {
			throw new UsernameNotFoundException("User " + username + " not found");
		}

		return new LoginInfo(user);
	}
}
